<template>
  <q-form @submit="submit" class="q-gutter-md dialog-content" style="height: 567px">
    <div class="gateway-container">
      <div class="left">
            <transition
              appear
              enter-active-class="animated bounceInDown"
              leave-active-class="animated fadeOut"

            >
              <img id="gateway" src="../../../../../statics/img/gateway.png" alt="gateway">
            </transition>
      </div>
      <div class="right">
        <q-card-section>
          <q-input style="width: 280px" v-model.trim="formData.gateWayId" outlined dense
                   :rules="[val => val && val.length > 0  || '请填写网关序列号',
                    val => val && /^[0-9a-zA-Z]*$/g.test(val) || '只能输入数字或者字母']">
            <template v-slot:before>
              <label class="text-right name label-width"><span class="text-red">*</span>网关序列号:</label>
            </template>
          </q-input>

          <q-select
            style="width: 280px"
            outlined
            dense
            emit-value
            map-options
            options-dense
            :options="productModelOptions"
            v-model="formData.productModel"
            :rules="[ val => val !== '' || ' 请选择产品型号']">
            <template v-slot:no-option>
              <div class="no-option" />
            </template>
            <template v-slot:before>
              <label class="text-right name bold" style="width: 100px"><span class="text-red">*</span>产品型号:</label>
            </template>
          </q-select>
        </q-card-section>
      </div>
    </div>
    <q-separator />
    <div class="dialog-footer text-center margin-t-10">
      <q-btn outline label="取消" color="primary" @click="hideDialog" class="q-mr-md"/>
      <q-btn unelevated label="下一步" color="primary" type="submit" :loading="submitting"/>
    </div>
  </q-form>
</template>

<script>
/* eslint-disable */
import { checkBoxNew, createBox, getBoxProducts } from '../../../../../boot/miot/list'
import { createPlcDevice } from '../../../../../boot/miot/plc-list'
import { mapGetters } from 'vuex'
import { Dialog } from 'quasar'

export default {
  name: 'new-gateway',
  data () {
    return {
      submitting: false,
      shows: true,
      formData: {
        gateWayId: '',
        productModel: '',
        productId: ''
      }
    }
  },
  props: {
    products: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    productModelOptions () {
      const data = []
      this.products.forEach(item => {
        data.push({
          value: item.productSN,
          label: item.productName
        })
      })
      return data
    },
    ...mapGetters(['client'])
  },
  methods: {
    hideDialog () {
      this.$emit('hideDialog')
    },

    async submit () {
      this.submitting = true
      const productItem = this.productModelOptions.find(item => item.value === this.formData.productModel)
      const productName = productItem.label
      // 检查是否是新盒子
      const rs = await checkBoxNew(this.formData.gateWayId, this.formData.productModel)
      const isNewCnc = rs.data
      this.$emit('cncType', !!rs.data)
      // 如果是新的cnc盒子
      if (isNewCnc) {
        try {
          const index = this.products.findIndex(item => item.productSN === this.formData.productModel)
          console.log(this.products, this.formData.productModel, index, 988833)
          const params = {
            gatewaySN: this.formData.gateWayId,
            productName: this.products[index].productName,
            productSN: this.products[index].productSN,
            gateWayType: 1
          }
          const { data } = await createPlcDevice(params)
          this.$emit('successSubmit', { ...data, productName, gatewaySN: this.formData.gateWayId })
        } catch (e) {
          this.$emit('failedSubmit')
        } finally {
          this.submitting = false
        }
      } else {
        // 获取老盒子序列号
        try {
          const oldProduct = await getBoxProducts()
          this.$emit('products', oldProduct.data?.products || [])
          const productItemOld = oldProduct.data?.products.find(item => item.name === productName)
          this.formData.productId = productItemOld.product_id
          const boxId = this.formData.productId + '_' + this.formData.gateWayId
          const rs = await createBox(this.formData.gateWayId, this.formData.productId, productName)
          if (!rs.success) {
            this.$emit('failedSubmit')
            return
          }
          try {
            this.$emit('loading', true)
            // 检查盒子是否在线
            await this.checkOnline()
            this.$emit('successSubmit', { productName, boxId })
          } catch (e) {
            this.$emit('failedSubmit')
          }
        } catch (e) {
          this.$emit('failedSubmit')
        } finally {
          this.submitting = false
        }
      }
    },
    /**
     * 检查盒子是否在线
     */
    checkOnline () {
      return new Promise((resolve, reject) => {
        if (this.client && this.client.connected) {
          const boxId =this.formData.productId + '_' + this.formData.gateWayId
          const subscribe = this.client.subscribe(
            `/topic/create/newBox/${boxId}`,
            (message) => {
              try {
                subscribe.unsubscribe()
                const ret = JSON.parse(message.body)
                if (ret && ret.data && ret.data.status === 'ONLINE') {
                  resolve()
                } else {
                  Dialog.create({
                    title: `<p class="dialog-notice-title">
                <i class="iconfont icontubiao-28" ></i>设备未在线，请检查设备网络</p>`,
                    html: true,
                    ok: {
                      unelevated: true,
                      label: '确认'
                    }
                  })
                  reject()
                }
              } catch (e) {
                console.log('解析socket内存报警错误' + e)
                reject()
              }
            }
          )
        } else {
          Dialog.create({
            title: `<p class="dialog-notice-title">
                <i class="iconfont icontubiao-28" ></i>websocket断开连接啦~请稍后重试</p>`,
            html: true,
            ok: {
              unelevated: true,
              label: '确认'
            }
          })
          reject()
        }
      })
    }
  }
}
</script>

<style scoped lang="stylus">
.gateway-container
  height 515px
  display flex
  .label-width
    width 100px
  .left,
  .right
    width 50%
    display flex
    align-items center
    justify-content center
#gateway
  animation-duration 1s
</style>
